package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.domain.Bed;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.BedMapper;
import com.zzyl.nursing.mapper.ContractMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import nonapi.io.github.classgraph.json.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author rouiqasy
 * @date 2025-01-02
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 老人办理申请入住
     *
     * @param checkInApplyDto 老人全部信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.判断老人是否已经入住
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<Elder>();
        CheckInElderDto elderDto = checkInApplyDto.getCheckInElderDto();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo, elderDto.getIdCardNo())
                .in(Elder::getStatus, 1, 4);
        Elder elder = elderMapper.selectOne(elderLambdaQueryWrapper);

        if (ObjectUtil.isNotEmpty(elder)) {//已入住
            throw new BaseException("老人已入住,请勿重复申请入住!");
        }

        //2.更新老人床位信息为入住
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        Bed bed = bedMapper.selectBedById(bedId);
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3.新增或更新老人
         elder = insertOrUpdateELder(checkInApplyDto, bed);//?获取返回值 签约信息要获取老人id

        //4.新增签约信息
        insertContractInfo(elder, checkInApplyDto.getCheckInContractDto(),checkInApplyDto.getCheckInConfigDto());
        //5.新增入住信息(同时保存家属信息到remark字段) ?为什么要返回值 入住配置需要入住信息id
        CheckIn checkIn = insertCheckInInfo(elder, checkInApplyDto.getCheckInConfigDto(), checkInApplyDto.getElderFamilyDtoList());

        //6.新增入住配置
        insertCheckConfig(checkIn,checkInApplyDto.getCheckInConfigDto());

    }

    /**
     *  新增入住配置信息
     * @param checkIn 入住信息
     * @param checkInConfigDto 入住配置信息
     */
    private void insertCheckConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
//        checkInConfig.setSortOrder(0); //排序编号默认为0
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     *  新增入住信息
     * @param elder 老人基本信息
     * @param checkInConfigDto  入住配置信息
     */
    private CheckIn insertCheckInInfo(Elder elder, CheckInConfigDto checkInConfigDto , List<ElderFamilyDto> ElderFamilyDto) {

        CheckIn checkIn = new CheckIn();

        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
//        checkIn.setStatus(0); //状态默认未入住(0)
//        checkIn.setSortOrder(0); //排序编号默认为0
        checkIn.setRemark(JSON.toJSONString(ElderFamilyDto));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     *  新增签约信息
     * @param elder 老人基本信息
     * @param checkInContractDto 签约信息
     * @param checkInConfigDto 入住配置信息
     */
    private void insertContractInfo(Elder elder, CheckInContractDto checkInContractDto, CheckInConfigDto checkInConfigDto) {



        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);
        contract.setElderId(Integer.valueOf(String.valueOf(elder.getId())));
        String contractNumber = CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
//        contract.setStatus(0);  //默认为未生效(0)
//        contract.setSortOrder(0); //默认为排序编号为0
        contractMapper.insert(contract);

    }

    /**
     * 新增或更新老人
     */
    private Elder insertOrUpdateELder(CheckInApplyDto checkInApplydto, Bed bed) {
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<Elder>();
        CheckInElderDto elderDto = checkInApplydto.getCheckInElderDto();
        wrapper.eq(Elder::getIdCardNo, elderDto.getIdCardNo());
        Elder elderInDB = elderMapper.selectOne(wrapper);
        if (ObjectUtil.isNotEmpty(elderInDB)) {//更新
            BeanUtils.copyProperties(elderDto, elderInDB);
            elderInDB.setStatus(1);
            elderInDB.setBedId(bed.getId());
            elderInDB.setBedNumber(bed.getBedNumber());
            elderMapper.updateById(elderInDB);
            return elderInDB;
        }else {//新增
            Elder elder = new Elder();
            BeanUtils.copyProperties(elderDto, elder);
            elder.setStatus(1);
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elderMapper.insert(elder);
            return elder;
        }
    }

    /**
     * 查询老人入住信息
     *
     * @param id 入住id
     * @return 老人入住信息
     */
    @Override
    public CheckInDetailVo getCheckInDetail(Long id) {
        //根据入住id查询老人信息
        CheckIn checkIn = checkInMapper.selectById(id);
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        //计算老人年龄
        // 定义日期格式
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 获取老人生日
        String birthDateString = elder.getBirthday();
        /*LocalDate birthDate = LocalDate.parse(birthDateString, formatter);
        LocalDate currentDate = LocalDate.now();
        Period period = Period.between(birthDate, currentDate);
        //计算出年龄
        int age = period.getYears();
        IdcardUtil工具功能多

        */
        int age = DateUtil.ageOfNow(birthDateString);//DateUtil工具类计算老人年龄

        CheckInElderVo checkInElderVo = new CheckInElderVo();
        checkInElderVo.setAge(age);
        BeanUtils.copyProperties(elder, checkInElderVo);

        //查询出入住配置信息
        LambdaQueryWrapper<CheckInConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckInConfig::getCheckInId,id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(wrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());

        //查询出合同信息
        Long elderId = elder.getId();
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId,elderId);
        Contract contract = contractMapper.selectOne(contractWrapper);

        //查询除chenkIn对象中将家属信息提取出来
        String familyStr = checkIn.getRemark();
//        List<ElderFamilyVo> familyVoList = JSONUtil.toList(familyStr, ElderFamilyVo.class);

        List<ElderFamilyVo> familyVoList = JSON.parseArray(familyStr,ElderFamilyVo.class);
        //5.封装checkInDetailVo中返回
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setElderFamilyVoList(familyVoList);
        return checkInDetailVo;
    }
}
